// 全局变量
let isEditing = false;
let editingId = null;

// 页面加载完成后获取宿舍列表
document.addEventListener('DOMContentLoaded', () => {
    fetchDormitories();
});

// 获取宿舍列表
async function fetchDormitories() {
    try {
        const response = await fetch('/api/dormitories');
        const dormitories = await response.json();
        displayDormitories(dormitories);
    } catch (error) {
        console.error('获取宿舍列表失败:', error);
        alert('获取宿舍列表失败');
    }
}

// 显示宿舍列表
function displayDormitories(dormitories) {
    const tbody = document.getElementById('dormitoryList');
    tbody.innerHTML = '';

    dormitories.forEach(dormitory => {
        const row = document.createElement('tr');
        row.innerHTML = `
            <td>${dormitory.building_no}</td>
            <td>${dormitory.room_no}</td>
            <td>${dormitory.floor}</td>
            <td>${dormitory.capacity}</td>
            <td>${dormitory.occupied}</td>
            <td>${dormitory.type}</td>
            <td>
                <button class="action-btn" onclick="viewDetails(${dormitory.id})">详情</button>
                <button class="action-btn edit-btn" onclick="editDormitory(${dormitory.id})">编辑</button>
                <button class="action-btn delete-btn" onclick="deleteDormitory(${dormitory.id})">删除</button>
            </td>
        `;
        tbody.appendChild(row);
    });
}

// 显示添加表单
function showAddForm() {
    isEditing = false;
    editingId = null;
    document.getElementById('formTitle').textContent = '添加宿舍';
    document.getElementById('addEditForm').reset();
    document.getElementById('dormitoryForm').style.display = 'block';
}

// 隐藏表单
function hideForm() {
    document.getElementById('dormitoryForm').style.display = 'none';
    document.getElementById('addEditForm').reset();
}

// 查看宿舍详情
async function viewDetails(id) {
    try {
        const response = await fetch(`/api/dormitories/${id}`);
        const data = await response.json();
        
        const detailsDiv = document.getElementById('dormitoryDetails');
        detailsDiv.innerHTML = `
            <div class="details-content">
                <p><strong>楼号：</strong>${data.dormitory.building_no}</p>
                <p><strong>宿舍号：</strong>${data.dormitory.room_no}</p>
                <p><strong>楼层：</strong>${data.dormitory.floor}</p>
                <p><strong>容量：</strong>${data.dormitory.capacity}</p>
                <p><strong>已住人数：</strong>${data.dormitory.occupied}</p>
                <p><strong>类型：</strong>${data.dormitory.type}</p>
                <h3>住宿学生列表：</h3>
                <div class="student-list">
                    ${data.students.length > 0 
                        ? `<ul>${data.students.map(student => 
                            `<li>${student.name} (${student.student_id})</li>`).join('')}</ul>`
                        : '<p>暂无学生入住</p>'}
                </div>
            </div>
        `;
        
        document.getElementById('detailsModal').style.display = 'block';
    } catch (error) {
        console.error('获取宿舍详情失败:', error);
        alert('获取宿舍详情失败');
    }
}

// 隐藏详情模态框
function hideDetails() {
    document.getElementById('detailsModal').style.display = 'none';
}

// 编辑宿舍信息
async function editDormitory(id) {
    try {
        const response = await fetch(`/api/dormitories/${id}`);
        const data = await response.json();
        const dormitory = data.dormitory;
        
        isEditing = true;
        editingId = id;
        document.getElementById('formTitle').textContent = '编辑宿舍信息';
        
        // 填充表单
        document.getElementById('buildingNo').value = dormitory.building_no;
        document.getElementById('roomNo').value = dormitory.room_no;
        document.getElementById('floor').value = dormitory.floor;
        document.getElementById('capacity').value = dormitory.capacity;
        document.getElementById('type').value = dormitory.type;
        
        document.getElementById('dormitoryForm').style.display = 'block';
    } catch (error) {
        console.error('获取宿舍信息失败:', error);
        alert('获取宿舍信息失败');
    }
}

// 删除宿舍
async function deleteDormitory(id) {
    if (!confirm('确定要删除这个宿舍吗？如果宿舍内有学生，将无法删除。')) {
        return;
    }

    try {
        const response = await fetch(`/api/dormitories/${id}`, {
            method: 'DELETE'
        });

        if (response.ok) {
            fetchDormitories(); // 刷新列表
            alert('删除成功');
        } else {
            const data = await response.json();
            throw new Error(data.error || '删除失败');
        }
    } catch (error) {
        console.error('删除宿舍失败:', error);
        alert(error.message || '删除宿舍失败');
    }
}

// 处理表单提交
async function handleSubmit(event) {
    event.preventDefault();

    const dormitoryData = {
        building_no: document.getElementById('buildingNo').value,
        room_no: document.getElementById('roomNo').value,
        floor: parseInt(document.getElementById('floor').value),
        capacity: parseInt(document.getElementById('capacity').value),
        type: document.getElementById('type').value
    };

    try {
        const url = isEditing ? `/api/dormitories/${editingId}` : '/api/dormitories';
        const method = isEditing ? 'PUT' : 'POST';

        const response = await fetch(url, {
            method: method,
            headers: {
                'Content-Type': 'application/json'
            },
            body: JSON.stringify(dormitoryData)
        });

        if (response.ok) {
            hideForm();
            fetchDormitories(); // 刷新列表
            alert(isEditing ? '更新成功' : '添加成功');
        } else {
            const data = await response.json();
            throw new Error(data.error || (isEditing ? '更新失败' : '添加失败'));
        }
    } catch (error) {
        console.error('操作失败:', error);
        alert(error.message || '操作失败');
    }
}